// app/extend/helper.js
const sd = require('silly-datetime'); // using silly-datetime
const jwt = require('jsonwebtoken');

const intformat = require('biguint-format');
const FlakeId = require('flake-idgen');

module.exports = {

    getId() {
        const flakeIdGen = new FlakeId({id: 100, datacenter: 200, worker: 300});
        return intformat(flakeIdGen.next(), 'dec')
    },
    /**
     * example: YYYY-MM-DD HH:mm:ss
     * @param {*} val  time
     * @param {String} str  YYYY-MM-DD HH:mm:ss
     */
    fmtDate(val, str = 'YYYY-MM-DD HH:mm:ss') {
        return sd.format(new Date(val), str);
    },
    encrypt: function (data, time) {
        //data加密数据，time过期时间
        return jwt.sign(data, this.app.config.jwt.secret, {expiresIn: time});
    },
    decrypt: function (token) {
        try {
            let data = jwt.verify(token, this.app.config.jwt.secret);
            return {
                token: true,
                ...data,
            };
        } catch (e) {
            return {
                token: false,
                data: e,
            };
        }
    },
};
